<script setup lang="ts">
import { ref, watch, reactive, h, shallowRef, toRaw } from 'vue'
import {
  NSpace,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  type FormRules,
  useMessage,
  NDataTable,
  NH3,
  NModal,
  NTooltip,
  NScrollbar,
  type FormInst,
  type DataTableColumns,
  NInputNumber
} from 'naive-ui'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import basicInfo from '@/components/CollectProcess/BasicInfo.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import FixedAction from '@/components/FixedAction.vue'
const route = useRoute()
const message = useMessage()
const id = ref()
const type = ref()
const code = ref()
const subItemCode = ref()
const idCopy = ref()
const form: any = reactive({
  compony: 1,
  yesNO: null,
  code: null,
  number: null,
  name: null,
  GroupName: null,
  rank: null,
  choice: null,
  itemName: null,
  assetCode: null,
  serialNumber: null,
  shelfNumber: null
})
const codeOptions = ref([
  { value: 1, label: 'ISBN' },
  { value: 2, label: '题名' },
  { value: 3, label: '馆藏码' }
])
const taozuOption = ref() //套组下拉

const tableLoading = ref()
const tableData: any = ref([])
const columns: DataTableColumns = [
  {
    title: 'ISBN',
    key: 'isbn',
    width: '5rem',
    align: 'center'
  },
  {
    title: '题名',
    key: 'title',
    width: '5rem',
    align: 'center'
  },
  {
    title: '出版者',
    key: 'publisher',
    width: '10rem',
    align: 'center'
  },
  {
    title: '版次印次',
    key: 'version',
    width: '10rem',
    align: 'center'
  },
  {
    title: '出版时间',
    key: 'publisherTime',
    width: '10rem',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            console.log(e)
            doubleCodeFn(e)
          }
        },
        {
          default: () => '套编'
        }
      )
    ]
  }
]
const formRules: FormRules = {
  GroupName: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'any',
    message: '套组名称不能为空',
    validator: () => {
      if (/^\s*$/.test(form.GroupName)) return new Error()
    }
  },
  loginName: {
    required: true,
    trigger: 'blur',
    message: '登录名不能为空'
  }
  // assetCode: {
  //   required: true,
  //   trigger: ['blur', 'input'],
  //   type: 'any',
  //   renderMessage: () => {
  //     if(!form.assetCode) return '馆藏码不能为空'
  //     else if (!form.assetCode?.match(/^[0-9]*$/))
  //     return '馆藏码是由数字组成不能有空格'

  //   },
  //   validator: () => {
  //     if (!form.assetCode||!form.assetCode?.match(/^[0-9]*$/)) return new Error()
  //   },
  //   message: '馆藏码不能为空'
  // }
}
const clueMethodOptions: any = reactive([])

const formInst = ref<FormInst | null>(null)
const formData = ref({} as any)
const modelJson = ref({} as ModelJson)
const otherJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeCode',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
const model = shallowRef<any>(baseModel)
const setModelJson = async (code?: string | null) => {
  if (!code) return (model.value = toRaw(baseModel))
  model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
    if (isArray(obj)) return [...obj, ...src]
  }) as ModelJson
}
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    await setModelJson(res.data.itemTypeCode)
    const { data } = res
    formData.value = Object.assign(
      {},
      // {
      //   itemName: data.itemName,
      //   receiveTime: data.receiveTime,
      //   itemTypeCode: data.itemTypeCode,
      //   itemTypeName: data.itemTypeName,
      //   itemNum: data.itemNum,
      //   receiveUser: data.receiveUser,
      //   notes: data.notes
      // },
      JSON.parse(data.jsonStr || '{}')
    )
    // fileList.value = data.fileList?.map((e: any, i: number) => ({
    //   id: i,
    //   name: e.name,
    //   status: 'finished',
    //   url: e.path,
    //   remoteId: e.id
    // }))
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
const GroupList: any = ref([])
const getInfo = async (subItemCode: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return

    // keysOf(res.data.detailVo).forEach((e) => {
    //   form[e] = res.data[e] as never
    // })
    console.log(res)
    GroupList.value = res.data?.itemsStagingList
    // ?.concat({
    //   ...res.data?.itemsStaging
    // })
    // await setModelJson(res.data?.detailVo?.itemTypeCode)
    form.assetCode = res.data?.itemsStaging?.assetCode || null
    form.itemName = res.data?.itemsStaging?.itemName
    form.serialNumber = res.data?.itemsStaging?.serialNumber
    form.shelfNumber = res.data?.itemsStaging?.shelfNumber
    // @ts-ignore
    form.choice = (res.data?.collectSetId || '') + ''
    res.data?.collectSetId && makeLineDetail(res.data?.collectSetId)
    res.data?.detailVo?.itemTypeCode && queryJsonBM(res.data?.detailVo?.itemTypeCode)
    //

    // formData.value = Object.assign(
    //   {},
    //   // {
    //   //   itemName: data.itemName,
    //   //   receiveTime: data.receiveTime,
    //   //   itemTypeCode: data.itemTypeCode,
    //   //   itemTypeName: data.itemTypeName,
    //   //   itemNum: data.itemNum,
    //   //   receiveUser: data.receiveUser,
    //   //   notes: data.notes
    //   // },
    //   JSON.parse(res.data.catalogInfo.contentJson || '{}')
    // )
    // res.data?.detailVo?.itemCode&&checkIsDetail(res.data?.detailVo?.itemCode)
    // modelJson.value = JSON.parse(res.data?.detailVo?.jsonStr)
    // debugger
    formData.value = JSON.parse(res.data?.catalogInfo)
  })
}

const modalVisible = ref(false)
const queryTableData = async (resetPage = false) => {
  if (!form.yesNO && !resetPage) {
    // message.info('请先输入筛选条件')
    return
  }
  console.log(resetPage)
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getCatalogInfo',
    override: {
      params: {
        type: form.compony,
        keyWords: form.yesNO
      }
    }
  })
  if (error) return message.error(error.message)
  tableData.value = res.data
  tableLoading.value = false
}
// 套编
const doubleCodeFn = async (e: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getAssetCodeDetailInfo',
    override: {
      params: {
        type: form.compony,
        keyWords: e.keywords
      }
    }
  })
  if (error) return message.error(error.message)
  let data = res.data
  formData.value = Object.assign(data)
}
const getTaozuFn = async () => {
  // 套组下拉接口
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getPullMenusCollectSet'
  })
  if (error) return message.error(error.message)

  taozuOption.value = res.data
}
getTaozuFn()
// 新增一条数据
const addGroupOpenFn = () => {
  modalVisible.value = true
}
const addGroupFn = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectSetSave',
    override: {
      data: {
        setName: form?.GroupName
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  getTaozuFn()
}
watch(
  () => route,
  async () => {
    if (route.path == '/collection/process/StepPlan/menu') {
      id.value = route.query?.id
      type.value = route.query?.type
      subItemCode.value = route.query?.id
      idCopy.value = route.query?.idCopy
      code.value = route.query?.code
      form.itemName = null
      form.assetCode = null
      form.serialNumber = null
      form.shelfNumber = null
      formData.value = {}
      getInfo(route.query?.id)
      queryTableData(true) //进入页面重新加载页面,true:去掉必填项
    }
  },
  { deep: true, immediate: true }
)
// 返回
const goBack = () => {
  history.back()
}
const baseFormRef = ref<FormInst | null>(null)
const loading = ref()
const submit = async () => {
  const validate = await Promise.all([
    // 暂时未使用
    new Promise((resolve, reject) => {
      baseFormRef.value?.validate((error: any) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
    // new Promise((resolve, reject) => {
    //   baseFormRef.value?.validate((error) => {
    //     if (error) return reject(error)
    //     resolve(true)
    //   })
    // })
  ])
  if (!validate.every(Boolean)) return
  loading.value = true
  console.log(formData.value)
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsSaveCatalogInfo',
    override: {
      data: {
        // subItemCode:route.query?.subItemCode,
        catalogInfo: {
          contentJson: JSON.stringify(formData.value),
          subItemCode: route.query?.id
        },
        itemsStaging: {
          itemName: form.itemName,
          assetCode: form.assetCode,
          serialNumber: form.serialNumber,
          shelfNumber: form.shelfNumber,
          itemSetId: form.choice,
          subItemCode: route.query?.id
        }

        // id: form.id,
        // ...form.itemsStaging
      }
    }
  })
  loading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  goBack()
}
const handleUpdateFormData = (key: string, value: unknown) => {
  formData.value[key] = value
}
//
const makeLineDetail = async (e: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'getListByItemSetId',
    uri: {
      // @ts-ignore
      itemSetId: e,
      // @ts-ignore
      subItemCode: route.query?.id
    }
  })
  if (error) return
  if (res.code !== 0) return

  GroupList.value = res.data
}
</script>
<template>
  <div class="menuStyle">
    <div style="width: 45%; margin-right: 10rem">
      <NSpace>
        <NSelect
          v-model:value="form.compony"
          filterable
          placeholder=""
          :options="codeOptions"
          style="width: 180px; margin-right: 10px"
          :on-change="() => (form.yesNO = null)"
        />
        <NInput
          v-if="form.compony == 2"
          v-model:value="form.yesNO"
          style="width: 180px; margin-right: 10px"
        />
        <NInputNumber
          v-else
          v-model:value="form.yesNO"
          :show-button="false"
          style="width: 180px; margin-right: 10px"
        />

        <NButton
          type="primary"
          style="width: 78px; margin-right: 10rem"
          ghost
          @click="queryTableData()"
        >
          查询
        </NButton>
        <NButton
          type="primary"
          style="width: 100rem; margin-bottom: 10rem"
          @click="addGroupOpenFn"
        >
          新增
        </NButton>
      </NSpace>
      <div class="topTitle">版本库 共{{ tableData.length || '0' }}条数据</div>
      <NDataTable
        :bordered="false"
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
      />
    </div>
    <div>
      <NScrollbar style="height: 80vh">
        <div>
          <NSpace>
            <NH3 prefix="bar">套组</NH3>
            <NSpace>
              套组选择：
              <NSelect
                v-model:value="form.choice"
                size="small"
                filterable
                placeholder=""
                :options="taozuOption"
                @update-value="makeLineDetail"
                style="width: 180px; margin-right: 10px"
              />
            </NSpace>
          </NSpace>

          <NForm
            require-mark-placement="left"
            :model="form"
            :rules="formRules"
            ref="baseFormRef"
            label-placement="left"
          >
            <NSpace
              :key="i.id"
              v-for="i in GroupList"
            >
              <NFormItem
                label="题名"
                path=""
              >
                <NInput
                  :value="i.itemName"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="馆藏码"
                path=""
              >
                <NInput
                  :value="i.assetCode"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="流水号"
                path="serialNumber"
              >
                <NInput
                  :value="i.serialNumber"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="排架号"
                path="time"
              >
                <NInput
                  :value="i.shelfNumber"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
            </NSpace>
            <NSpace>
              <NFormItem
                label="题名"
                path=""
              >
                <NInput
                  v-model:value="form.itemName"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="馆藏码"
                path="assetCode"
              >
                <NInput
                  v-model:value="form.assetCode"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="流水号"
                path="name"
              >
                <NInput
                  v-model:value="form.serialNumber"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
              <NFormItem
                label="排架号"
                path="time"
              >
                <NInput
                  v-model:value="form.shelfNumber"
                  class="inputGroup"
                  disabled
                />
              </NFormItem>
            </NSpace>
          </NForm>
        </div>
        <!-- <div class="topTitle">基本信息</div> -->
        <basicInfo
          :id="idCopy"
          :type-show="type"
          :code="code"
        />
        <div>
          <NH3 prefix="bar">详编</NH3>

          <DynamicPageForm
            ref="formInst"
            :form-model="otherJson"
            :model="formData"
            :form-data="formData"
            label-placement="left"
            require-mark-placement="left"
            label-width="140rem"
            @update:value="handleUpdateFormData"
          />
          <FixedAction>
            <NSpace justify="center">
              <NButton
                type="primary"
                style="width: 78px"
                @click="submit"
                :loading="loading"
              >
                提交
              </NButton>
              <NButton
                style="width: 78px"
                ghost
                @click="goBack"
              >
                返回
              </NButton>
            </NSpace>
          </FixedAction>
        </div>
      </NScrollbar>
      <NModal
        :auto-focus="false"
        v-model:show="modalVisible"
      >
        <VDialogContent
          @close="modalVisible = false"
          @submit="addGroupFn"
          title="套组"
        >
          <NForm
            require-mark-placement="left"
            :model="form"
            :rules="formRules"
            ref="groupFormRef"
            label-placement="left"
            label-width="80"
          >
            <NFormItem
              label="套组名称"
              path="GroupName"
            >
              <NInput
                v-model:value="form.GroupName"
                class="inputGroup"
              />
            </NFormItem>
          </NForm>
        </VDialogContent>
      </NModal>
    </div>
  </div>
</template>
<style scoped lang="scss">
.menuStyle {
  display: flex;
  padding: 10px;

  .topTitle {
    font-size: 22px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    color: #5fb17f;
    margin-bottom: 10rem;
  }

  .inputWH {
    width: 300rem;
  }

  .inputGroup {
    width: 140rem;
  }
}
</style>
